package com.pay.cloud.fragment;

import com.pay.cloud.DataFactory;
import com.pay.cloud.DataStore;
import com.pay.cloud.DeviceUtils;
import com.pay.cloud.HttpUtil;
import com.pay.cloud.StatusListener;
import com.pay.cloud.cpay.MyCloudPay;

import org.json.JSONObject;

import static com.pay.cloud.fragment.TipFragment.TipType.WAIT;

public class ShopBindFragment extends TipVerticalFragment {
    private StatusListener listener;
    private String code;
    public ShopBindFragment(String code, StatusListener listener) {
        super(WAIT, "正在绑定设备");
        this.code = code;
        this.listener = listener;
    }

    @Override
    public boolean useNetwork() {
        return true;
    }

    @Override
    public void execute() throws Exception {
        code = code + "&sn=" + DeviceUtils.sn(getActivity());
        String jsonString = HttpUtil.get(code);
        JSONObject json = new JSONObject(jsonString);
        if (!json.getString("status").equals("0")) {
            onError("[" + json.getString("status") + "]" + json.getString("description"));
            return;
        }
        JSONObject setting = json.getJSONObject("use_device_setting");

        String outMchId = setting.getString("out_mch_id");
        String outSubMchId = setting.getString("out_sub_mch_id");
        String cloudCashierId = setting.getString("cloud_cashier_id");
        String authenType = setting.getString("authen_type");
        String authenKey = setting.getString("authen_key");
        String outShopId = setting.getString("out_shop_id");
        String shopName = setting.getString("shop_name");
        String deviceId = setting.getString("device_id");
        String deviceName = setting.getString("device_name");
        String staffId = setting.getString("staff_id");
        String staffName = setting.getString("staff_name");

        DataStore store = DataFactory.getDataStore();
        store.setOutMchId(outMchId);
        store.setOutSubMchId(outSubMchId);
        store.setCloudCashierId(cloudCashierId);
        store.setAuthenType(authenType);
        store.setAuthenKey(authenKey);
        store.setOutShopId(outShopId);
        store.setShopName(shopName);
        store.setDeviceId(deviceId);
        store.setDeviceName(deviceName);
        store.setStaffId(staffId);
        store.setStaffName(staffName);

        MyCloudPay.init(getActivity());

        onSuccess();
    }

    @Override
    public void onError(String msg) {
        speak("设备绑定失败");
        listener.onError(msg);
    }

    private void onSuccess() {
        speak("设备绑定成功");
        listener.onSuccess("设备绑定成功");
    }

}
